"use client"

import { useState } from "react"
import {
  CopyOutlined,
  EditOutlined,
  DeleteOutlined,
  GlobalOutlined,
  ApiOutlined,
  DatabaseOutlined,
  CloudOutlined,
  AppstoreOutlined,
} from "@ant-design/icons"
import { message, Popconfirm } from "antd"
import type { Host, Department, Project } from "../types"

interface HostCardProps {
  host: Host
  departments: Department[]
  projects: Project[]
  onEdit: (host: Host) => void
  onDelete: (id: string) => void
}

const HostCard = ({ host, departments, projects, onEdit, onDelete }: HostCardProps) => {
  const [isDeleting, setIsDeleting] = useState(false)

  const department = departments.find((d) => d.id === host.departmentId)
  const project = projects.find((p) => p.id === host.projectId)

  const handleCopy = () => {
    const content = host.isComment ? host.commentText : `${host.ip} ${host.domain}`
    navigator.clipboard.writeText(content)
    message.success("已复制到剪贴板")
  }

  const handleDelete = () => {
    if (isDeleting) return
    setIsDeleting(true)

    try {
      onDelete(host.id)
      message.success("删除成功")
    } catch (error) {
      message.error("删除失败")
    } finally {
      setIsDeleting(false)
    }
  }

  const getTypeIcon = () => {
    switch (host.type) {
      case "frontend":
        return <GlobalOutlined />
      case "backend":
        return <ApiOutlined />
      case "database":
        return <DatabaseOutlined />
      case "cache":
        return <CloudOutlined />
      default:
        return <AppstoreOutlined />
    }
  }

  const getTypeText = () => {
    switch (host.type) {
      case "frontend":
        return "前端"
      case "backend":
        return "后端"
      case "database":
        return "数据库"
      case "cache":
        return "缓存"
      default:
        return "其他"
    }
  }

  // 生成随机颜色
  const getRandomColor = () => {
    // 使用主机ID作为种子生成一致的颜色
    const seed = host.id.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0)
    const h = seed % 360
    const s = 70
    const l = 90
    return `hsl(${h}, ${s}%, ${l}%)`
  }

  // 获取标题的首字母
  const getTitleInitial = () => {
    if (!host.title) return "?"
    return host.title.charAt(0).toUpperCase()
  }

  // 如果是注释行，显示不同的卡片样式
  if (host.isComment) {
    return (
      <div className="host-card" style={{ border: "1px dashed var(--gray-300)", backgroundColor: "var(--gray-50)" }}>
        <div className="host-card-content">
          <div style={{ fontFamily: "monospace", fontSize: "13px", color: "var(--gray-600)" }}>{host.commentText}</div>
        </div>
      </div>
    )
  }

  return (
    <div className="host-card">
      <div className="host-card-content">
        <div className="host-card-header">
          <div className="host-card-icon" style={{ backgroundColor: getRandomColor() }}>
            {getTitleInitial()}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 className="host-card-title" title={host.title}>
                {host.title}
              </h3>
              <span style={{ fontSize: "12px", color: "var(--gray-500)", whiteSpace: "nowrap" }}>
                {new Date(host.lastUpdated).toLocaleDateString()}
              </span>
            </div>
            <div className="host-card-meta">
              {project && <span className="badge badge-blue">{project.name}</span>}
              {host.type && (
                <span className={`type-badge type-${host.type}`}>
                  {getTypeIcon()}
                  <span>{getTypeText()}</span>
                </span>
              )}
            </div>
          </div>
        </div>

        {host.description && (
          <div className="host-card-description" title={host.description}>
            {host.description}
          </div>
        )}

        <div style={{ marginTop: "12px", fontSize: "13px" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <span style={{ color: "var(--gray-700)" }}>IP:</span>
              <span style={{ fontFamily: "monospace", fontWeight: "500" }}>{host.ip}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <span style={{ color: "var(--gray-700)" }}>域名:</span>
              <span style={{ fontFamily: "monospace", fontWeight: "500" }}>{host.domain}</span>
            </div>
          </div>
        </div>
      </div>

      <div className="host-card-footer">
        <button className="host-card-button" onClick={() => onEdit(host)}>
          <EditOutlined />
          <span>编辑</span>
        </button>
        <button className="host-card-button" onClick={handleCopy}>
          <CopyOutlined />
          <span>复制</span>
        </button>
        <Popconfirm title="确定要删除这条记录吗？" onConfirm={handleDelete} okText="确定" cancelText="取消">
          <button className="host-card-button danger">
            <DeleteOutlined />
            <span>{isDeleting ? "删除中..." : "删除"}</span>
          </button>
        </Popconfirm>
      </div>
    </div>
  )
}

export default HostCard
